//
//  CTPhotoBrowserItemView.swift
//  CTPhotoBrowser
//
//  Created by Andney Jack on 2021/2/25.
//

import UIKit

public class CTPhotoBrowserItemView: UIView, CTCycleScrollItemViewProtocol, UIScrollViewDelegate {
    public var isShowed: Bool = false
    public var didFetchImage: Bool = false

    /// 单击事件回调
    public var singleTapHandler: ((_ itemView: CTPhotoBrowserItemView) -> Void)?
    /// 长按事件回调
    public var longPressHandler: ((_ itemView: CTPhotoBrowserItemView) -> Void)?
    /// 当前显示的图片
    public var currentImage: UIImage? {
        return didFetchImage ? imageView.image : nil
    }

    public private(set) var imageView = UIImageView()

    private var m_longPressEnabled: Bool = false
    private var scrollView = UIScrollView()
    private var longPressGesture: UILongPressGestureRecognizer?
    private weak var indicatorView: CTPhotoBrowserIndicatorView?

    public var isLongPressEnabled: Bool {
        get {
            return m_longPressEnabled
        }
        set {
            m_longPressEnabled = newValue
            if m_longPressEnabled {
                if longPressGesture == nil {
                    longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureHandle(_:)))
                    longPressGesture?.minimumPressDuration = 0.8
                    scrollView.addGestureRecognizer(longPressGesture!)
                }
                longPressGesture?.isEnabled = true

            } else {
                // 移除手势
                if let gesture = longPressGesture {
                    gesture.isEnabled = false
                    removeGestureRecognizer(gesture)
                    longPressGesture = nil
                }
            }
        }
    }

    // MARK: -

    override public init(frame: CGRect) {
        super.init(frame: frame)
        loadUI()
    }

    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func layoutSubviews() {
        scrollView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
        indicatorView?.center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)

        reset()

        super.layoutSubviews()
    }

    func loadUI() {
        scrollView.minimumZoomScale = 0.6
        scrollView.maximumZoomScale = 3.0
        scrollView.zoomScale = 1.0
        scrollView.delegate = self
        addSubview(scrollView)

        scrollView.addSubview(imageView)

        // 添加手势
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(gestureHandle(_:)))
        doubleTap.numberOfTapsRequired = 2
        doubleTap.numberOfTouchesRequired = 1
        scrollView.addGestureRecognizer(doubleTap)

        let singleTap = UITapGestureRecognizer(target: self, action: #selector(gestureHandle(_:)))
        singleTap.numberOfTapsRequired = 1
        singleTap.numberOfTouchesRequired = 1
        scrollView.addGestureRecognizer(singleTap)

        singleTap.require(toFail: doubleTap) // 只能有一个手势存在
    }

    @objc private func gestureHandle(_ gesture: UIGestureRecognizer) {
        if let tap = gesture as? UITapGestureRecognizer {
            if tap.numberOfTapsRequired == 2 {
                // 双击手势
                let touchPoint = gesture.location(in: gesture.view)
                if scrollView.zoomScale <= 1.0 {
                    let scaleX = touchPoint.x + scrollView.contentOffset.x // 需要放大的图片的X点
                    let scaleY = touchPoint.y + scrollView.contentOffset.y // 需要放大的图片的Y点
                    scrollView.zoom(to: CGRect(x: scaleX, y: scaleY, width: 10, height: 10), animated: true)
                } else {
                    scrollView.setZoomScale(1.0, animated: true) // 还原
                }

            } else {
                // 单击手势
                singleTapHandler?(self)
            }

        } else if let _ = gesture as? UILongPressGestureRecognizer {
            // 长按手势
            longPressHandler?(self)
        }
    }

    // MARK: - ———— UIScrollViewDelegate

    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }

    public func scrollViewDidZoom(_ scrollView: UIScrollView) {
        imageView.center = getCenterOfScollViewContent(scrollView)
    }

//    indicatorView

    // MARK: - ———— Public

    /// 恢复默认状态
    public func reset() {
        if let image = imageView.image, image.size.width > 0, image.size.height > 0 {
            let scale = image.size.height / image.size.width
            imageView.bounds = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.width * scale)
        } else {
            imageView.bounds = CGRect.zero
        }
        imageView.center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)

        scrollView.zoomScale = 1.0
    }

    public func addIndicatorView() {
        removeIndicatorView()

        let indicator = CTPhotoBrowserIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
        indicator.indicatorStyle = .circle
        indicator.center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
        addSubview(indicator)

        indicatorView = indicator
    }

    public func removeIndicatorView() {
        if indicatorView != nil {
            indicatorView?.removeFromSuperview()
            indicatorView = nil
        }
    }

    public func setIndicatorProgress(_ progress: CGFloat) {
        indicatorView?.progress = progress
    }

    // MARK: - ———— Util

    func getCenterOfScollViewContent(_ scrollView: UIScrollView) -> CGPoint {
        let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) / 2.0, 0.0)
        let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) / 2.0, 0.0)

        return CGPoint(x: scrollView.contentSize.width / 2.0 + offsetX,
                       y: scrollView.contentSize.height / 2.0 + offsetY)
    }
}
